package com.wecode.core.exception;

import com.wecode.core.constant.ErrorConstant;
import com.wecode.core.utils.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 统一处理所有未处理异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.OK)
    public ResponseObject handleGlobalException(Exception e) {
        ResponseObject responseObject = new ResponseObject();
        responseObject.setCode(ErrorConstant.SERVER_ERROR.getCode());
        e.printStackTrace();
        return responseObject;
    }

    /**
     * 自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BusinessException.class})
    @ResponseStatus(HttpStatus.OK)
    public ResponseObject handleRestException(BusinessException e) {
        ResponseObject responseObject = new ResponseObject();
        responseObject.setCode(e.code);
        responseObject.setMsg(e.msg);
        return responseObject;
    }
}
